import mitt from 'mitt'

/**
 * 事件总线类型定义
 */
type Events = {
  [key: string]: any
}

/**
 * 创建事件总线实例
 */
const emitter = mitt<Events>()

/**
 * 事件总线工具函数
 */
export default emitter

/**
 * 发射事件
 */
export const emit = (event: string, data?: any) => {
  emitter.emit(event, data)
}

/**
 * 监听事件
 */
export const on = (event: string, handler: Function) => {
  emitter.on(event, handler)
}

/**
 * 移除事件监听
 */
export const off = (event: string, handler?: Function) => {
  if (handler) {
    emitter.off(event, handler)
  } else {
    emitter.off(event)
  }
}

/**
 * 清除所有事件监听
 */
export const clear = () => {
  emitter.all.clear()
}
